import vue from '../main.js'

class DownloadUtil {
  download(fileName) {
    // 注意：请求中responseType一定要设置为arraybuffer，不然无法解析返回内容
    vue.$axios.get(`/api/common/download?filePath=${fileName}&delete=true`, {responseType: 'arraybuffer'})
    .then(response => {
      console.log(response);
      this.convertResponseToBlob(response)
    }).catch(error => {
      console.log(error);
    })
  }

  convertResponseToBlob(response) {
    let fileName = response.headers['content-disposition'].match(/fileName=(.*)/)[1];
    let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, decodeURI(fileName));
    } else {
      let blobURL = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = blobURL;
      // 设置下载文件名称
      a.setAttribute("download", decodeURI(fileName));
      if(typeof a.download === 'undefined') {
        // 兼容有些浏览器不支持download属性
        a.setAttribute('target', '_blank');
      }
      document.body.appendChild(a);
      a.click();
      document.body.removeAttribute(a);
      // 释放blobURL地址
      window.URL.revokeObjectURL(blobURL);
    }
  }

}

const downloadUtil = new DownloadUtil();

export default downloadUtil;